function UpdateEpochDataOutputInDatabase(subject, outputBE)
%UPDATEEPOCHDATAOUTPUTINDATABASE Used by EpochData (in Final) to write
%information about epochs to the database.

if ~(nargin==2); help UpdateEpochDataOutputInDatabase; error('Incorrect number of arguments'); end;

global Database;

%% Check..
cCode = strcmp(Database.subjects_header, 'Code');
rSubject = strcmp({Database.subjects{:,cCode}}, subject); %#ok<*CCAT>
if ~any(rSubject); error(['Subject ''' subject ''' not found']); end

%% Find all columns
cSubject = strcmp(Database.epochs_header, 'Subject');
cCondition = strcmp(Database.epochs_header, 'Condition');
cShort = strcmp(Database.epochs_header, 'Short');
cNrOfEpochs = strcmp(Database.epochs_header, 'NrOfEpochs');
cDatecode = strcmp(Database.epochs_header, 'Datecode');
cConfiguration = strcmp(Database.epochs_header, 'Configuration');
cFilename = strcmp(Database.epochs_header, 'Filename');


%% Write or replace data for every epoched set
for i = fieldnames(outputBE.Datasets)'
    x = outputBE.Datasets.(cell2mat(i));
    % Find the data..
    
    % Find row for subject/condition
    rSubject = strcmp({Database.epochs{:,cSubject}}, subject);
    rCondition = strcmp({Database.epochs{:,cCondition}}, x.name);
    rCurrentRow = rCondition & rSubject;
    
    if ~any(rCurrentRow) % not in database, create new
        Database.epochs(end+1,:) = cell(size(Database.epochs_header));
        rCurrentRow = size(Database.epochs, 1);
        Database.epochs{rCurrentRow, cSubject} = subject;
        Database.epochs{rCurrentRow, cCondition} = x.name;
        Database.epochs{rCurrentRow, cShort} = CreateShortFor(x.name);
    end
    % Update the information
    Database.epochs{rCurrentRow, cNrOfEpochs} = x.nrOfEpochsFound;
    Database.epochs{rCurrentRow, cDatecode} = x.datecode;
    Database.epochs{rCurrentRow, cConfiguration} = x.configuration;
    Database.epochs{rCurrentRow, cFilename} = x.dataFilename;
end

SaveTable('epochs');

end

function [ccode] = CreateShortFor(condition)
[ cname ccode ctype ] = GetConditionByName( condition );
end